const Base = require('../../base.js');

module.exports = class extends Base {
  async indexAction() {
    let data = this.post()
    let userInfo = await this.session('user_info')
    if (!userInfo) return this.fail(-1, '未登录授权')
    if (data.type == 1) {
      // 使用余额支付
      let dealList = await this.model('deal/index').all(userInfo._id)
      let money = 0
      let addType = ['commission', 'deduct', 'charge']
      let reduceType = ['upgrade', 'cash']
      dealList.forEach(item => {
        if (addType.indexOf(item.type) != -1) {
          money += item.money
        } else if (reduceType.indexOf(item.type) != -1) {
          money -= item.money
        }
      })
      if (money < think.vipNum(data.vip).price) return this.fail(-1, '余额不足请使用，支付宝支付')
      /// 生成交易订单
      let deal = await this.model('deal/index').add({
        vip: data.vip,
        type: 'upgrade',
        uid: userInfo._id,
        money: think.vipNum(data.vip).price,
        status: 1,
        remark: '升级' + think.vipNum(data.vip).name + ', 通过余额扣款方式开通'
      })
      /// 修改用户VIP状态
      await this.model('user/index').edit({
        _id: userInfo._id,
        vip: data.vip
      })
      return this.json({
        status: 200, mewssage: 'success', data: 1
      })
    } else {
      /// 通过支付宝付款
      let alipaySdk = await think.alipaySdk()
      let deal = await this.model('deal/index').add({
        vip: data.vip,
        type: 'upgrade',
        uid: userInfo._id,
        money: 0,
        status: 0,
        remark: '升级' + think.vipNum(data.vip).name + ', 通过支付宝付款开通，不变动账户余额'
      })
      let id = deal._id.toString()
      let result = await this.model('alipay/index').wapPay(alipaySdk, {
        notifyUrl: 'http://' + this.ctx.host + '/api/deal/charge?id=' + deal._id,
        outTradeNo: id,
        totalAmount: think.vipNum(data.vip).price,
        subject: 'VIP升级',
        body: '升级' + think.vipNum(data.vip).name
      })
      this.json({
        status: 200, message: 'success', data: {
          deal, result
        }
      })
    }
  }
};
